package com.example.basic_config.interceptor;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description 自定义拦截器
 * @author ljw
 * @date 2021/9/2 7:13
 */
public class MyInterceptor extends HandlerInterceptorAdapter {

    /**
     * 在请求发生前执行
     * @param
     * @author ljw
     * @date 2021/9/2 7:19
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        return true;
    }

    /**
     * 在请求完成后执行
     * @param
     * @author ljw
     * @date 2021/9/2 7:19
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (long) request.getAttribute("startTime");
        request.removeAttribute("startTime");
        long endTime = System.currentTimeMillis();
        System.out.println("本次请求处理时间为：" +(endTime - startTime) + "ms");
        request.setAttribute("handlingTime", endTime-startTime);
    }
}
